package com.itshops.filter;

import com.itshops.entity.User;
import com.itshops.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 用户用户进行自动登录
 */
@WebFilter("/login.jsp")
public class AutoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            String content=null;//存放数据
            for (Cookie cookie:cookies
                 ) {
                //获取cookie信息
                if (cookie.getName().equals("autoCookie")){
                   content= cookie.getValue();
                }
                if (content!=null){
                    //解析数据
                    String[] split = content.split(":");
                    String username=split[0];
                    String password=split[1];
                    UserServiceImpl userService = new UserServiceImpl();
                    try {
                        User user = userService.login(username, password);
                        if (user!=null){
                            //可以自动登录
                           HttpServletResponse resp = (HttpServletResponse) servletResponse;
                           //存放到session
                            HttpSession session = req.getSession();
                            session.setAttribute("loginUser",user);
                           req.getRequestDispatcher("/index.jsp").forward(req,resp);
                        }else {
                            filterChain.doFilter(servletRequest,servletResponse);
                        }
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }else {
                    filterChain.doFilter(servletRequest,servletResponse);
                }

            }

        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
